<template>
  <div class="content-box" v-loading="isLoadIframe">
    <iframe
      class="item"
      :class="{ cover_item: isCoverIframe }"
      :src="src"
      frameborder="0"
      name="content"
      id="content"
      ref="content"
      @load="postMsg"
      seamless
    ></iframe>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import NProgress from 'nprogress';
export default {
  data() {
    return {
      src: undefined,
      isLoadIframe: false, // Iframe是否加载完成
      isCoverIframe: false, // Iframe是否全屏
    };
  },
  computed: {
    ...mapState(['isCollapse']),
  },
  watch: {
    $route() {
      this.init();
    },
  },
  mounted() {
    window.addEventListener('message', this.receiveMsg);
    // this.init();
  },
  methods: {
    // 收到子窗口消息
    receiveMsg(info) {
      let { data } = info;
      if (data.source !== 'content') {
        return;
      }
      const { action } = data;
      if (action === 'methodRun') {
        // 子级调用父级方法, 可以考虑是否可以接收数组, 一次调用多个方法, 方法是顺序执行, 还是Promise.all并行, 调用多个方法,参数如何接收
        // 子级要调用那个组件的方法等, 多预留扩展接口
        const { funName, params = undefined } = data;
        this[funName](params);
      }
    },
    // 弹出消息提示
    showTopMessage(options) {
      this.$message(options);
    },
    getIframe() {
      return window.frames['content'];
    },
    postMsg() {
      this.isLoadIframe = true;
      this.init();
    },
    init() {
      NProgress.start();
      this.isLoadIframe = true;

      const { path, name, meta } = this.$route;
      const { orgin, pathName } = meta;

      // 初始化iframe后，判断啊url是否一样，
      // 不一样 替换url重新加载url，
      // 一样 通知子应用根据name跳转路由
      if (this.src === `${orgin}${pathName}`) {
        this.sendMsg2content({ type: 'changeRoute', params: { path, name } });
        this.sendMsg2content({
          type: 'isCollapse',
          params: { collapse: this.isCollapse },
        });
        this.isLoadIframe = false;
        NProgress.done();
      } else {
        this.src = `${orgin}${pathName}`;
      }
    },
    // 设置Iframe全屏
    setIframeCover() {
      this.isCoverIframe = true;
    },
    // 取消Iframe全屏
    cancelIframeCover() {
      this.isCoverIframe = false;
    },
  },
};
</script>

<style lang="less" scoped>
.content-box {
  flex: 1;
  overflow: hidden;

  .item {
    position: fixed;
    z-index: 1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100vw;
    height: 100vh;
  }

  .cover_item {
    z-index: 2;
  }
}
</style>
